package com.example.chap9.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.chap9.entity.Book;
import com.example.chap9.service.BookServiceImpl;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.*;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/book")
@CacheConfig(cacheNames = "book")
public class BookController {

    @Autowired
    BookServiceImpl bookServer;

    @Resource
    CacheManager cacheManager;

    @GetMapping("")
    @Cacheable( key = "#root.targetClass+'bookList'")
    public List<Book> getBooks() {
        return bookServer.list();
    }

    @GetMapping("/{id}")
    @Cacheable( key = "#id")
    public Book getId(@PathVariable Integer id) {
        return bookServer.getById(id);
    }

    @DeleteMapping("/{id}")
    @Cacheable( key = "#id")
    public String delBook(@PathVariable Integer id) {
        System.out.println("假装删除数据库的书 id：" + id);
        return "删除成功";
    }

    @PutMapping()
    @Caching(
            put = @CachePut( key = "#book.id"),
            evict = @CacheEvict( key = "#root.targetClass+'bookList'")
    )
    public Book update(@RequestBody Book book) {
        bookServer.saveOrUpdate(book);
        return book;
    }

    @Cacheable(key="(#condition.bookName!=null?#condition.bookName:'')+(#condition.category!=null?#condition.category:'')+(#condition.author!=null?#condition.author:'')")  //定义缓存的键为拼接的参数,值是方法的返回值
    @PostMapping
    public List<Book> searchBooks(@RequestBody Book condition){ //查找一本书
        System.out.println("条件查询,并添加到缓存，key为搜索条件的组合");
        System.out.println("condition:"+condition);

        LambdaQueryWrapper<Book> queryWrapper= new LambdaQueryWrapper<>();
        if (StringUtils.hasText(condition.getName())) {
            queryWrapper.like(Book::getName,condition.getName());
        }
        if (StringUtils.hasText(condition.getCategory())) {
            queryWrapper.like(Book::getCategory,condition.getCategory());
        }
        if (StringUtils.hasText(condition.getAuthor())) {
            queryWrapper.like(Book::getAuthor,condition.getAuthor());
        }

        return bookServer.list(queryWrapper);
    }
}
